package concurrentpractice;

import lombok.Data;
import lombok.experimental.Accessors;
import org.junit.Test;

public class SynchronizedSolution {

  private enum Printer {
    NUMBER, LETTER
  }

  @Data
  @Accessors(chain = true)
  private class Scheduler {

    private Printer enabledPrinter = Printer.NUMBER;
  }

  private final Scheduler scheduler = new Scheduler();

  @Test
  public void verifySynchronized() throws InterruptedException {
    Thread numberPrintThread = new Thread(() -> {
      for (int i = 1; i < 52; i = i + 2) {
        synchronized (scheduler) {
          try {
            while (scheduler.getEnabledPrinter() != Printer.NUMBER) {
              scheduler.wait();
            }
            for (int j = 0; j < 2; j++) {
              System.out.print(i + j);
            }
            scheduler.setEnabledPrinter(Printer.LETTER);
            scheduler.notify();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    });
    Thread letterPrintThread = new Thread(() -> {
      for (char i = 'A'; i <= 'Z'; i++) {
        synchronized (scheduler) {
          try {
            while (scheduler.getEnabledPrinter() != Printer.LETTER) {
              scheduler.wait();
            }
            System.out.print(i);
            scheduler.setEnabledPrinter(Printer.NUMBER);
            scheduler.notify();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    });
    numberPrintThread.start();
    letterPrintThread.start();

    numberPrintThread.join();
    letterPrintThread.join();
  }
}
